package controlador;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import modelo.bd.exception.DAOException;
import modelo.dominio.Usuario;
import modelo.servicio.Usuarios;

public class UsuarioControlador extends HttpServlet {

    private String html;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=ISO-8859-1");
        PrintWriter out = response.getWriter();
        String accion = request.getParameter("ac") == null ? "" : request.getParameter("ac");
        html = "";
        try {
            if (accion.equals("li")) {
                getServletContext().getRequestDispatcher("/jsp/usuario/login.jsp").forward(request, response);
            } else if (accion.equals("lg")) {
                validaSesion(request, response);
                //out.println(html);
            } else if (accion.equals("lo")) {
                request.getSession().invalidate();
//                request.getSession(true).invalidate();
                response.sendRedirect(getServletContext().getContextPath());
            }
        } catch (Exception ex) {
            out.println(ex.getMessage());

        } finally {
            out.close();
        }
    }

// <editor-fold defaultstate="collapsed" desc="Metodos HttpServlet. Click en el signo + izquierdo para editar el codigo.">
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
// </editor-fold>

    public void validaSesion(HttpServletRequest request, HttpServletResponse response)
            throws DAOException {
        HttpSession session = request.getSession(true);
        String login, contrasena, cia;
        login = request.getParameter("login") == null ? "" : request.getParameter("login");
        contrasena = request.getParameter("contrasena") == null ? "" : request.getParameter("contrasena");
        cia = request.getParameter("cmb_cia") == null ? "" : request.getParameter("cmb_cia");
        try {
            Usuario actual = Usuarios.instancia().obtener(login, contrasena);
            if (actual != null 
                    && modelo.servicio.Companias.instancia().obtener(cia) != null) {
                session.setAttribute("sUsuario", actual.getLogin());
                session.setAttribute("sNombre", actual.getNombre());
//                session.setAttribute("sPerfil", usuarioActual.getPerfil());
                session.setAttribute("sCompania", cia);
                response.sendRedirect(getServletContext().getContextPath());
            } else {
                session.invalidate();
                getServletContext().getRequestDispatcher("/usuario?ac=li").forward(request, response);
//                response.sendRedirect(getServletContext().getContextPath() + "/usuario?ac=li");
            }
        } catch (Exception ex) {
            html = "Error en usuario o contrasenia, Intentar otra vez"
                    + "<br/>Error:" + ex.getMessage();
        }
    }
}
